﻿using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace VkSample91
{
    [ModulePriority(ModulePriority.RenderPass)]
    public class PipelineModule : VulkanModule, IVulkanRenderWapperModule
    {
        private readonly ILogger<PipelineModule> _Logger;

        public PipelineModule(ILogger<PipelineModule> logger)
        {
            _Logger = logger;
        }

        public VulkanRenderWapper RenderWapper { get; set; }

        protected override async Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var lDevice = graphicsManager.VulkanDevice;
                var pipeCache = lDevice.PipelineCache;
                var disapatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
                var presentPass = disapatcher.SwapchainRenderPass;
                var area = RenderWapper.RenderArea;
                var basePath = AppContext.BaseDirectory;
                var shaders = Path.Combine(basePath, "Assets", "Shaders");
                var document = await JsonDocument.ParseAsync(File.OpenRead(Path.Combine(shaders, "Pipeline.json")));
                var pipelineJson = document.RootElement;

                var camera = graphicsManager.CreateCamera("main", new Vector3(0, 10.0f, 60.0f), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                float aspcet = (float)area.Width / area.Height;
                camera.SetProjectMatrix(-aspcet, 1.0f, 1.5f, 1500);
                camera.SetViewport(0, 0, area.Width, area.Height, 0.0f, 1.0f);

                var oitSemaphore = lDevice.CreateSemaphore();
                var imageAvailableSemaphore = disapatcher.ImageAvailableSemaphore;
                var renderFinishedSemaphore = disapatcher.RenderFinishSemaphore;
                var fence = lDevice.CreateFence();

                var dImage1 = lDevice.CreateDepthBufferFromJson(pipelineJson.GetProperty("DepthBufferCreateOption").GetRawText());
                var dImage2 = lDevice.CreateDepthBufferFromJson(pipelineJson.GetProperty("DepthBufferCreateOption").GetRawText());
                var oitPass = lDevice.CreateRenderPassFromJson("OIT", new Format[] { Format.R8G8B8A8Unorm, Format.D16Unorm },
                    RenderPassMode.Normal, pipelineJson.GetProperty("OITPass").GetRawText());
                var oitAttach = lDevice.CreateImageFromJson(pipelineJson.GetProperty("OITAttachment").GetRawText(), new Extent3D(area.Width, area.Height, 1),
                    MemoryPropertyFlags.MemoryPropertyDeviceLocalBit);
                oitPass.CreateFrameBuffer(new VulkanImageView[] { oitAttach, dImage1 }, area.Width, area.Height);
                oitPass.ConfigBeginInfo((option) =>
                {
                    option.RenderArea = new Rect2D { Extent = new Extent2D(area.Width, area.Height), Offset = new Offset2D { X = 0, Y = 0 } };
                    option.ClearValues = new ClearValue[] 
                    {
                        new ClearValue() { Color = new ClearColorValue(0.0f, 0.0f, 0.0f, 0.0f) },
                        new ClearValue() { DepthStencil = new ClearDepthStencilValue(1.0f, 0) }
                    };
                });
                var oitListBufferData = graphicsManager.CreateLocalStorageTexelBufferData("OITListBuffer", Format.R32G32B32A32Uint, 4096 * 4096 * 3);
                var oitHeadPointerData = graphicsManager.CreateLocalReadWriteTextureData("OITHeaderPointer", lDevice, pipelineJson.GetProperty("OITPassHeadPointer").GetRawText(),
                    new Extent3D(area.Width, area.Height, 1), FormatFeatureFlags.FormatFeatureStorageImageBit | FormatFeatureFlags.FormatFeatureTransferDstBit);
                var oitSampler = lDevice.CreateSamplerFromJson("OITSampler", pipelineJson.GetProperty("OITSampler").GetRawText());
                var oitHeadPointerTex = graphicsManager.CreateTexture("OITHeaderPointer", oitHeadPointerData, oitSampler, descriptorType: DescriptorType.StorageImage);
                var oitListBufferTex = graphicsManager.CreateTexture("OITListBuffer", oitListBufferData, null, descriptorType: DescriptorType.StorageTexelBuffer);

                VulkanShaderInfo[] infos = new VulkanSPVShaderInfo[]
                {
                    new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "OITVert", new FileInfo(Path.Combine(shaders,"oitvert.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "OITFrag", new FileInfo(Path.Combine(shaders, "oitfrag.spv")))
                };
                await Task.WhenAll(infos[0].LoadShader(), infos[1].LoadShader());
                var oitPipeline = graphicsManager.CreateEmptyPipeline("OITPipeline")
                    .BuildPipelineLayoutFromJson(pipelineJson.GetProperty("OITSetLayoutCreateOptions").GetRawText(),
                    pipelineJson.GetProperty("OITPipelineLayoutCreateOption").GetRawText())
                    .BuildStorageBuffer(0, 0, 8, SharingMode.Exclusive)
                    .BindPipelineTexture(oitListBufferTex, 1, 0)
                    .BindPipelineTexture(oitHeadPointerTex, 1, 1)
                    .BuildGraphicsPipelineFromJson(oitPass, pipeCache, infos, pipelineJson.GetProperty("OITPipeline").GetRawText());

                var presentHeadPointerTex = graphicsManager.CreateTexture("PresentHeaderPointer", oitHeadPointerData, oitSampler, descriptorType: DescriptorType.StorageImage);
                var presentListBufferTex = graphicsManager.CreateTexture("PresentListBuffer", oitListBufferData, null, descriptorType: DescriptorType.StorageTexelBuffer);
                VulkanShaderInfo[] pInfo = new VulkanSPVShaderInfo[]
                {
                    new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "PresentVert", new FileInfo(Path.Combine(shaders,"presentVert.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "PresentFrag", new FileInfo(Path.Combine(shaders, "presentFrag.spv")))
                };
                await Task.WhenAll(pInfo[0].LoadShader(), pInfo[1].LoadShader());
                var presentPipeline = graphicsManager.CreateEmptyPipeline("PresentPipeline")
                    .BuildPipelineLayoutFromJson(pipelineJson.GetProperty("PresentSetLayoutCreateOptions").GetRawText(), null)
                    .BindPipelineTexture(presentListBufferTex, 0, 0)
                    .BindPipelineTexture(presentHeadPointerTex, 0, 1)
                    .BuildGraphicsPipelineFromJson(presentPass, pipeCache, pInfo, pipelineJson.GetProperty("PresentPipeline").GetRawText());

                var mCommand = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreatePrimaryCommandBuffers(2);
                var oit = graphicsManager.CreatePrimaryRenderGroup("OIT", oitPipeline)
                    .Binding(mCommand[0], lDevice, oitPass, new Semaphore[] { oitSemaphore.RawHandle }, new Fence[0]);
                oit.SetCamera(camera);
                oit.CreateGroupRenderingAction((builder) => builder.UseMiddleware<OITGroupRenderingMiddleware>());
                oit.CreateItemRenderingAction((builder) => builder.UseMiddleware<OITItemGroupRenderingMiddleware>());
                var present = graphicsManager.CreatePrimaryRenderGroup("Present", presentPipeline)
                    .Binding(mCommand[1], lDevice, presentPass, new Semaphore[] { oitSemaphore.RawHandle, imageAvailableSemaphore, renderFinishedSemaphore }, new Fence[] { fence.RawHandle });
                present.SetCamera(camera);
                present.CreateGroupRenderingAction((builder) => builder.UseMiddleware<PresentGroupRendingMiddleware>());
                present.CreateItemRenderingAction((builder) => builder.UseMiddleware<PresentItemGroupReneringMiddleware>());
                oit.AddChildren(present);

                var scene = RenderWapper.CreateAndCutScene<Scene>("Main", oit, typeof(TransformSystem), typeof(InputSystem));
                scene.AddSceneModules(typeof(AssetsModule));
                await scene.LoadSceneModules();
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            }
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
